<template>
  <div class="music-player">
    <!-- 左侧歌曲信息 -->
    <div class="song-info">
      <el-image 
        class="cover" 
        :src="songs[currentIndex].cover" 
        fit="cover"
        :preview-src-list="[songs[currentIndex].cover]"
      />
      <div class="song-text">
        <div class="title">{{ songs[currentIndex].name }}</div>
        <div class="singer">{{ songs[currentIndex].singer }}</div>
      </div>
    </div>

    <!-- 中间播放控制区 -->
    <div class="player-controls">
      <div class="control-buttons">
        <!-- 播放模式按钮 -->
        <el-popover
          placement="top"
          :width="200"
          trigger="click"
        >
          <template #reference>
            <el-button circle>
              <i :class="playModeIcon"></i>
            </el-button>
          </template>
          <div class="play-mode-list">
            <div 
              v-for="mode in playModes" 
              :key="mode.type"
              class="play-mode-item"
              :class="{ active: currentMode === mode.type }"
              @click="changePlayMode(mode.type)"
            >
              <i :class="mode.icon"></i>
              <span>{{ mode.text }}</span>
            </div>
          </div>
        </el-popover>

        <el-button-group>
          <el-button circle @click="prevSong">
            <i class="fas fa-step-backward"></i>
          </el-button>
          <el-button circle @click="togglePlay">
            <i :class="isPlaying ? 'fas fa-pause' : 'fas fa-play'"></i>
          </el-button>
          <el-button circle @click="nextSong">
            <i class="fas fa-step-forward"></i>
          </el-button>
        </el-button-group>
        <el-button circle>
          <i class="far fa-heart"></i>
        </el-button>
      </div>
      
      <!-- 进度条 -->
      <div class="progress-bar">
        <span class="current-time">{{ formatTime(currentTime) }}</span>
        <el-slider
          class="progress"
          v-model="progress"
          :show-tooltip="false"
          @change="onProgressChange"
        />
        <span class="total-time">{{ formatTime(duration) }}</span>
      </div>
    </div>

    <!-- 右侧音量控制等 -->
    <div class="right-controls">
      <el-button circle @click="toggleMute">
        <i :class="isMuted ? 'fas fa-volume-mute' : 'fas fa-volume-up'"></i>
      </el-button>
      <el-slider
        class="volume-slider"
        v-model="volume"
        :show-tooltip="false"
        @change="onVolumeChange"
      />
      <!-- 音乐列表按钮 -->
      <el-popover
        placement="top"
        :width="400"
        trigger="click"
      >
        <template #reference>
          <el-button circle>
            <i class="fas fa-list"></i>
          </el-button>
        </template>
        <div class="playlist">
          <div class="playlist-header">
            <span class="title">播放列表 ({{ songs.length }})</span>
            <div class="actions">
              <el-button link type="primary" @click="clearPlaylist">
                <i class="fas fa-trash"></i> 清空
              </el-button>
            </div>
          </div>
          <el-scrollbar height="400px">
            <div 
              v-for="(song, index) in songs" 
              :key="index" 
              class="playlist-item"
              :class="{ active: currentIndex === index }"
              @click="playSong(index)"
            >
              <div class="song-index">{{ index + 1 }}</div>
              <el-image 
                class="song-cover" 
                :src="song.cover" 
                fit="cover"
              />
              <div class="song-content">
                <div class="song-name">{{ song.name }}</div>
                <div class="song-singer">{{ song.singer }}</div>
              </div>
              <div class="duration">{{ song.duration }}</div>
              <div class="item-actions">
                <el-button link type="primary" @click.stop="downloadSong(song)">
                  <i class="fas fa-download"></i>
                </el-button>
                <el-button link type="danger" @click.stop="removeSong(index)">
                  <i class="fas fa-times"></i>
                </el-button>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </el-popover>
    </div>
  </div>
  <!-- 添加音频元素 -->
  <audio 
    ref="audioRef"
    :src="songs[currentIndex].url"
    @timeupdate="onTimeUpdate"
    @loadedmetadata="onLoadedMetadata"
    @ended="onEnded"
  ></audio>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import {
  ArrowLeft,
  ArrowRight,
  VideoPlay,
  VideoPause,
  Star,
  Microphone,
  Mute,
  Menu
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 音频相关的响应式数据
const audioRef = ref<HTMLAudioElement | null>(null)
const isPlaying = ref(false)
const isMuted = ref(false)
const currentIndex = ref(0)
const currentTime = ref(0)
const duration = ref(0)
const progress = ref(0)
const volume = ref(50)

// 播放模式相关
type PlayMode = 'order' | 'loop' | 'random' | 'single-loop' | 'single'

const playModes = [
  {
    type: 'order' as PlayMode,
    icon: 'fas fa-sort-numeric-down',
    text: '顺序播放'
  },
  {
    type: 'loop' as PlayMode,
    icon: 'fas fa-redo',
    text: '列表循环'
  },
  {
    type: 'random' as PlayMode,
    icon: 'fas fa-random',
    text: '随机播放'
  },
  {
    type: 'single-loop' as PlayMode,
    icon: 'fas fa-redo',
    text: '单曲循环'
  },
  {
    type: 'single' as PlayMode,
    icon: 'fas fa-music',
    text: '单曲播放'
  }
]

const currentMode = ref<PlayMode>('order')

// 根据当前播放模式显示对应图标
const playModeIcon = computed(() => {
  const mode = playModes.find(m => m.type === currentMode.value)
  return mode?.icon
})

// 切换播放模式
const changePlayMode = (mode: PlayMode) => {
  currentMode.value = mode
  // 当切换到单曲循环模式时，重新播放当前歌曲
  if (mode === 'single-loop' && isPlaying.value) {
    playSong(currentIndex.value)
  }
}

// 播放控制方法
const togglePlay = () => {
  if (!audioRef.value) return
  if (isPlaying.value) {
    audioRef.value.pause()
  } else {
    audioRef.value.play()
  }
  isPlaying.value = !isPlaying.value
}

const playSong = (index: number) => {
  currentIndex.value = index
  isPlaying.value = false
  // 等待DOM更新后播放
  setTimeout(() => {
    if (audioRef.value) {
      audioRef.value.play()
        .then(() => {
          isPlaying.value = true
        })
        .catch((error) => {
          console.error('播放失败:', error)
          isPlaying.value = false
        })
    }
  }, 100)
}

const nextSong = () => {
  switch (currentMode.value) {
    case 'order':
      if (currentIndex.value < songs.value.length - 1) {
        playSong(currentIndex.value + 1)
      }
      break
    case 'loop':
      currentIndex.value = (currentIndex.value + 1) % songs.value.length
      playSong(currentIndex.value)
      break
    case 'random':
      const nextIndex = Math.floor(Math.random() * songs.value.length)
      playSong(nextIndex)
      break
    case 'single-loop':
      playSong(currentIndex.value)
      break
    case 'single':
      if (currentIndex.value < songs.value.length - 1) {
        playSong(currentIndex.value + 1)
      }
      break
  }
}

const prevSong = () => {
  switch (currentMode.value) {
    case 'order':
      if (currentIndex.value > 0) {
        playSong(currentIndex.value - 1)
      }
      break
    case 'loop':
      const prevIndex = (currentIndex.value - 1 + songs.value.length) % songs.value.length
      playSong(prevIndex)
      break
    case 'random':
      const randomIndex = Math.floor(Math.random() * songs.value.length)
      playSong(randomIndex)
      break
    case 'single-loop':
    case 'single':
      playSong(currentIndex.value)
      break
  }
}

// 音量控制
const toggleMute = () => {
  if (!audioRef.value) return
  audioRef.value.muted = !audioRef.value.muted
  isMuted.value = audioRef.value.muted
}

const onVolumeChange = (value: number) => {
  if (!audioRef.value) return
  audioRef.value.volume = value / 100
  if (value === 0) {
    isMuted.value = true
  } else {
    isMuted.value = false
  }
}

// 进度控制
const onProgressChange = (value: number) => {
  if (!audioRef.value) return
  const time = (value / 100) * duration.value
  audioRef.value.currentTime = time
  currentTime.value = time
}

// 音频事件处理
const onTimeUpdate = () => {
  if (!audioRef.value) return
  currentTime.value = audioRef.value.currentTime
  progress.value = (currentTime.value / duration.value) * 100
}

const onLoadedMetadata = () => {
  if (!audioRef.value) return
  duration.value = audioRef.value.duration
}

const onEnded = () => {
  switch (currentMode.value) {
    case 'single':
      isPlaying.value = false
      break
    case 'single-loop':
      playSong(currentIndex.value)
      break
    default:
      nextSong()
  }
}

// 时间格式化
const formatTime = (time: number) => {
  const minutes = Math.floor(time / 60)
  const seconds = Math.floor(time % 60)
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

// 组件挂载时初始化音频设置
onMounted(() => {
  if (audioRef.value) {
    audioRef.value.volume = volume.value / 100
    audioRef.value.onerror = (e) => {
      console.error('音频加载错误:', e)
      isPlaying.value = false
      // 可以在这里添加错误提示
    }
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (audioRef.value) {
    audioRef.value.pause()
  }
})

// 歌曲列表
const songs = ref([
  {
    name: '清く正しくカブタック',
    singer: '草尾毅',
    description: '铁甲小宝 片头曲',
    url: 'https://music.163.com/song/media/outer/url?id=28285777.mp3',
    duration: '03:48',
    cover: 'http://p1.music.126.net/q4lWarUS-yGnzJDTa_SIUA==/6009930557523167.jpg'
  },
  {
    name: '逆転ロックンロール!!',
    singer: '草尾毅',
    description: '铁甲小宝 片尾曲',
    url: 'https://music.163.com/song/media/outer/url?id=28285786.mp3',
    duration: '03:15',
    cover: 'https://p1.music.126.net/0ookhRcuCcqJk_WIOUctRg==/18535567022910052.jpg?param=200y200'
  },
  {
    name: '大追跡!~スターピースを追いかけろ~',
    singer: '水木一郎',
    description: '铁甲小宝 插曲',
    url: 'https://music.163.com/song/media/outer/url?id=28285778.mp3',
    duration: '03:12',
    cover: 'https://p1.music.126.net/zA_5bszebRmNo9b9KzDYzA==/19136999882070942.jpg?param=200y200'
  }
])

// 修改 downloadSong 方法
/**
 * 
 * @param song 
 * 后端实现一个代理接口，大致逻辑如下：
    1.接收前端传来的音乐 URL
    2.在后端发起请求获取音乐文件
    3.将音乐文件返回给前端
 */
const downloadSong = async (song: any) => {
  try {
    ElMessage.info('开始下载...')
    const response = await fetch(song.url, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
      }
    })
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${song.name} - ${song.singer}.mp3`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  }
}

// 修改 removeSong 方法，添加确认提示
const removeSong = async (index: number) => {
  if (songs.value.length === 1) {
    ElMessage.warning('播放列表至少需要保留一首歌')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除这首歌吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const isCurrentSong = index === currentIndex.value
    songs.value.splice(index, 1)
    
    if (isCurrentSong) {
      if (index >= songs.value.length) {
        playSong(0)
      } else {
        playSong(index)
      }
    } else if (index < currentIndex.value) {
      currentIndex.value--
    }
  } catch {
    // 用户取消删除
  }
}

// 添加清空播放列表方法
const clearPlaylist = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空播放列表吗？将保留当前播放的歌曲',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 保留当前播放的歌曲
    const currentSong = songs.value[currentIndex.value]
    songs.value = [currentSong]
    currentIndex.value = 0
    
  } catch {
    // 用户取消清空
  }
}

// 修改 addAndPlaySong 方法
const addAndPlaySong = (song: any) => {
  // 转换歌曲数据格式
  const playerSong = {
    name: song.title,
    singer: song.artist,
    cover: song.cover,
    url: song.url,
    description: song.description || '',
    duration: song.duration || '00:00'
  }
  
  // 检查歌曲是否已经在列表中
  const existingIndex = songs.value.findIndex(s => s.url === playerSong.url)
  
  if (existingIndex === -1) {
    // 如果歌曲不在列表中，添加到列表
    songs.value.push(playerSong)
    // 播放新添加的歌曲
    playSong(songs.value.length - 1)
  } else {
    // 如果歌曲已经在列表中，直接播放
    playSong(existingIndex)
  }
}

// 导出方法供其他组件使用
defineExpose({
  addAndPlaySong
})
</script>

<style scoped>
.music-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 70px;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-shadow: var(--el-box-shadow-light);
  z-index: 999;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.song-info {
  display: flex;
  align-items: center;
  width: 250px;
}

.cover {
  width: 50px;
  height: 50px;
  border-radius: var(--el-border-radius-base);
  margin-right: 12px;
}

.song-text {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title {
  font-size: 14px;
  color: var(--el-text-color-primary);
  font-weight: bold;
}

.singer {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.player-controls {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.control-buttons {
  display: flex;
  align-items: center;
  gap: 16px;
}

.progress-bar {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 20px;
}

.progress {
  flex: 1;
}

.current-time, .total-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  width: 45px;
}

.right-controls {
  width: 250px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 16px;
}

.volume-slider {
  width: 100px;
}

/* 播放列表样式 */
.playlist {
  padding: 0;
  background: var(--el-bg-color);
}

.playlist-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.playlist-header .title {
  font-size: 14px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.playlist-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.3s;
  gap: 8px;
}

.song-cover {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  flex-shrink: 0;
}

.song-content {
  flex: 1;
  min-width: 0;
}

.song-name {
  font-size: 14px;
  color: #333;
  line-height: 1.2;
  margin-bottom: 4px;
  @include text-ellipsis;
}

.song-singer {
  font-size: 12px;
  color: #999;
  line-height: 1.2;
  @include text-ellipsis;
}

.duration {
  width: 45px;
  font-size: 12px;
  color: #999;
  margin-right: 16px;
  text-align: right;
}

.item-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.playlist-item:hover {
  background-color: #f5f5f5;
}

.playlist-item:hover .item-actions {
  opacity: 1;
}

.playlist-item.active {
  background-color: #f0f0f0;
}

.playlist-item.active .song-name {
  color: var(--el-color-primary);
}

/* 调整按钮样式 */
.item-actions .el-button {
  padding: 4px;
}

.item-actions .el-button i {
  font-size: 14px;
}

/* 列表容器样式 */
.playlist {
  background: #fff;
  border-radius: 4px;
}

.playlist-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
}

.playlist-header .title {
  font-size: 14px;
  color: #333;
}

/* 滚动条样式 */
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

:deep(.el-scrollbar__bar.is-horizontal) {
  display: none;
}

/* 播放模式列表样式 */
.play-mode-list {
  padding: 8px;
}

.play-mode-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  border-radius: var(--el-border-radius-base);
}

.play-mode-item:hover {
  background: var(--el-fill-color-light);
}

.play-mode-item.active {
  color: var(--el-color-primary);
}

.play-mode-item i {
  margin-right: 8px;
  width: 16px;
  text-align: center;
}

/* 调整弹出层的 z-index */
:deep(.el-popover) {
  z-index: 1000 !important;
}

/* 添加序号样式 */
.song-index {
  width: 30px;
  color: #999;
  font-size: 14px;
  text-align: center;
}
</style>
